/**
 * '/dashboard/a'   => ['/dashboard', '/dashboard/a']
 * '/dashboard/a/b' => ['/dashboard', '/dashboard/a', '/dashboard/a/b']
 * '/a/b/c/d'       => ['/a', '/a/b', '/a/b/c', '/a/b/c/d']
 */
export const p2p = (str: string): string[] => {
  // 1. 将 str 使用 '/' 分割, 且将 '' 给去掉
  //    // '/dashboard/a'  => ['', 'dashboard', 'a']  => ['dashboard', 'a']
  const arr = str.split("/").filter((item) => item);
  // 2. 使用 reduce 来遍历
  const tmp = arr.reduce((result, item, index) => {
    if (index === 0) {
      result.push(`/${item}`);
    } else {
      result.push(`${result[index - 1]}/${item}`);
    }
    return result;
  }, [] as string[]);
  // 3. 返回 tmp
  return tmp;
};

/**
 * 递归树形数据
 * @param list
 * @param parentId
 */
export function deepTree(list: API.MenuObject[], parentId: null | number) {
  return list
    .filter((item) => item.parentId === parentId)
    .map((item) => {
      const curItem = { ...item, key: item.id };
      // 用当前 curItem.id 作为 parentId 来找他的子级
      const children = deepTree(list, curItem.id);
      // 判断 children 是否存在
      if (children.length) {
        curItem.children = children;
      }
      return curItem;
    });
}

/**
 * 递归树形数据
 * @param list
 */
export function deepTreeTwo(list: API.MenuObject[]) {
  // 最终结果集合
  const result: API.MenuObject[] = [];
  // 映射对象
  const map: { [key: string]: API.MenuObject } = {};

  // 构造出完整的 map 对象
  for (const item of list) {
    map[item.id] = { ...item, key: item.id, children: [] };
  }

  // 再基于 list 做循环
  for (const item of list) {
    const newItem = map[item.id];

    if (item.parentId === null) {
      result.push(newItem);
    } else {
      if (Object.prototype.hasOwnProperty.call(map, item.parentId)) {
        map[item.parentId].children?.push(newItem);
      } else {
        result.push(newItem);
      }
    }
  }

  return result;
}

/**
 * id 所表示的节点是否在 list 中属于叶子节点
 * @param list
 * @param id
 * @return boolean
 */
export function isLeaf(list: API.MenuObject[], id: number) {
  return !list.find((item) => item.parentId === id);
}

/**
 * 将 tree 数据转换成 antd 的 Menu 组件的 items 数据
 */
export function generateMenus(tree: any) {
  return tree.map((item: any) => {
    const children = generateMenus(item.children);
    const newItem: any = {
      key: item.router || item.id,
      label: item.name,
    };
    if (children.length) {
      newItem.children = children;
    }
    return newItem;
  });
}
